// pages/dress_calendar/dress_calendar.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        time: '12:30',
        currentFilter: 'all',
        calendarView: 'month',
        currentYear: 2024,
        currentMonth: 2, // JavaScript月份从0开始，这里是3月
        currentMonthDisplay: '2024年3月',
        selectedDate: '2024-03-22',
        selectedDateDisplay: '今日档期安排（3月22日）',
        
        // 筛选礼服编号
        dressCode: '',
        dressName: '',
        
        // 日历日期数据
        calendarDays: [],
        
        // 当日事件
        dayEvents: [
          {
            id: 1,
            time: '10:00',
            title: '婚纱取件',
            client: '周小姐',
            dress: '法式蕾丝鱼尾婚纱',
            type: 'pickup',
            typeText: '取件'
          },
          {
            id: 2,
            time: '14:30',
            title: '量体服务',
            client: '陈小姐',
            dress: '轻奢浪漫纱裙',
            type: 'measure',
            typeText: '量体'
          }
        ],
        
        // 所有事件数据
        allEvents: [
          {
            id: 1,
            date: '2024-03-01',
            time: '10:00',
            title: '取件: 周小姐',
            client: '周小姐',
            dress: '法式蕾丝鱼尾婚纱',
            dressCode: 'WD2401',
            type: 'pickup',
            typeText: '取件'
          },
          {
            id: 2,
            date: '2024-03-01',
            time: '15:30',
            title: '试装: 李小姐',
            client: '李小姐',
            dress: '公主梦幻拖尾婚纱',
            dressCode: 'WD1825',
            type: 'try',
            typeText: '试装'
          },
          {
            id: 3,
            date: '2024-03-02',
            time: '14:00',
            title: '量体: 张小姐',
            client: '张小姐',
            dress: '白色缎面修身礼服套装',
            dressCode: 'SD0512',
            type: 'measure',
            typeText: '量体'
          },
          {
            id: 4,
            date: '2024-03-04',
            time: '16:00',
            title: '归还: 赵先生',
            client: '赵先生',
            dress: '经典黑色燕尾服套装',
            dressCode: 'SD0615',
            type: 'return',
            typeText: '归还'
          },
          {
            id: 5,
            date: '2024-03-05',
            time: '09:30',
            title: '维护: WD1825',
            client: '',
            dress: 'WD1825 公主梦幻拖尾婚纱',
            dressCode: 'WD1825',
            type: 'maintenance',
            typeText: '维护'
          },
          {
            id: 6,
            date: '2024-03-08',
            time: '11:00',
            title: '取件: 钱小姐',
            client: '钱小姐',
            dress: '白色缎面修身礼服套装',
            dressCode: 'SD0512',
            type: 'pickup',
            typeText: '取件'
          },
          {
            id: 7,
            date: '2024-03-13',
            time: '13:30',
            title: '试装: 王先生',
            client: '王先生',
            dress: '经典黑色燕尾服套装',
            dressCode: 'SD0615',
            type: 'try',
            typeText: '试装'
          },
          {
            id: 8,
            date: '2024-03-15',
            time: '10:00',
            title: '取件: 孙小姐',
            client: '孙小姐',
            dress: '星光奢华晚礼服',
            dressCode: 'ED0723',
            type: 'pickup',
            typeText: '取件'
          },
          {
            id: 9,
            date: '2024-03-15',
            time: '11:30',
            title: '试装: 刘小姐',
            client: '刘小姐',
            dress: '轻奢浪漫纱裙',
            dressCode: 'WD2403',
            type: 'try',
            typeText: '试装'
          },
          {
            id: 10,
            date: '2024-03-15',
            time: '14:00',
            title: '量体: 郑先生',
            client: '郑先生',
            dress: '经典黑色燕尾服套装',
            dressCode: 'SD0615',
            type: 'measure',
            typeText: '量体'
          },
          {
            id: 11,
            date: '2024-03-15',
            time: '16:00',
            title: '取件: 何小姐',
            client: '何小姐',
            dress: '法式蕾丝鱼尾婚纱',
            dressCode: 'WD2401',
            type: 'pickup',
            typeText: '取件'
          },
          {
            id: 12,
            date: '2024-03-15',
            time: '17:30',
            title: '归还: 吴先生',
            client: '吴先生',
            dress: '经典黑色燕尾服套装',
            dressCode: 'SD0615',
            type: 'return',
            typeText: '归还'
          },
          {
            id: 13,
            date: '2024-03-22',
            time: '10:00',
            title: '取件: 周小姐',
            client: '周小姐',
            dress: '法式蕾丝鱼尾婚纱',
            dressCode: 'WD2401',
            type: 'pickup',
            typeText: '取件'
          },
          {
            id: 14,
            date: '2024-03-22',
            time: '14:30',
            title: '量体: 陈小姐',
            client: '陈小姐',
            dress: '轻奢浪漫纱裙',
            dressCode: 'WD2403',
            type: 'measure',
            typeText: '量体'
          },
          {
            id: 15,
            date: '2024-03-23',
            time: '15:00',
            title: '试装: 周小姐',
            client: '周小姐',
            dress: '法式蕾丝鱼尾婚纱',
            dressCode: 'WD2401',
            type: 'try',
            typeText: '试装'
          },
          {
            id: 16,
            date: '2024-03-25',
            time: '14:00',
            title: '量体: 周小姐',
            client: '周小姐',
            dress: '法式蕾丝鱼尾婚纱',
            dressCode: 'WD2401',
            type: 'measure',
            typeText: '量体'
          },
          {
            id: 17,
            date: '2024-03-28',
            time: '15:30',
            title: '试装: 周小姐',
            client: '周小姐',
            dress: '法式蕾丝鱼尾婚纱',
            dressCode: 'WD2401',
            type: 'try',
            typeText: '试装'
          }
        ]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 更新当前时间
        this.updateTime();
        this.getTimerID = setInterval(this.updateTime, 60000);
        
        // 获取当前日期
        const today = new Date();
        const year = today.getFullYear();
        const month = today.getMonth();
        const date = today.getDate();
        
        // 更新日历数据
        this.setData({
          currentYear: year,
          currentMonth: month,
          selectedDate: `${year}-${(month + 1).toString().padStart(2, '0')}-${date.toString().padStart(2, '0')}`,
          selectedDateDisplay: `今日档期安排（${month + 1}月${date}日）`,
          currentMonthDisplay: `${year}年${month + 1}月`
        });
        
        // 如果有传递的礼服编号，则设置礼服编号并修改标题
        if (options.dressCode) {
            // 根据礼服编号查找对应的礼服名称
            const dress = this.findDressByCode(options.dressCode);
            const dressName = dress ? dress : options.dressCode;
            
            this.setData({
                dressCode: options.dressCode,
                dressName: dressName,
                selectedDateDisplay: `${dressName} 档期安排`
            });
        }
        
        // 生成日历数据
        this.generateCalendarDays();
        
        // 加载当日事件
        this.loadDayEvents();
    },

    // 根据礼服编号查找礼服名称
    findDressByCode: function(code) {
        // 遍历所有事件找到对应的礼服
        for (const event of this.data.allEvents) {
            if (event.dressCode === code) {
                return event.dress.split(" ").pop(); // 移除编号前缀
            }
        }
        return code; // 如果找不到，返回编号
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        clearInterval(this.getTimerID);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    updateTime: function() {
        const date = new Date();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        this.setData({
          time: `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
        });
    },

    // 生成日历数据
    generateCalendarDays: function() {
        const { currentYear, currentMonth, allEvents, currentFilter, dressCode } = this.data;
        
        // 获取月份第一天是星期几(0-6)
        const firstDay = new Date(currentYear, currentMonth, 1).getDay();
        
        // 获取月份总天数
        const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
        
        // 获取上个月天数
        const daysInPrevMonth = new Date(currentYear, currentMonth, 0).getDate();
        
        // 今天日期
        const today = new Date();
        const isCurrentMonth = today.getFullYear() === currentYear && today.getMonth() === currentMonth;
        const todayDate = today.getDate();
        
        let calendarDays = [];
        
        // 上个月的日期
        for (let i = 0; i < firstDay; i++) {
          const prevMonthDay = daysInPrevMonth - firstDay + i + 1;
          const prevMonth = currentMonth === 0 ? 11 : currentMonth - 1;
          const prevYear = currentMonth === 0 ? currentYear - 1 : currentYear;
          const dateString = `${prevYear}-${(prevMonth + 1).toString().padStart(2, '0')}-${prevMonthDay.toString().padStart(2, '0')}`;
          
          calendarDays.push({
            day: prevMonthDay,
            dateString: dateString,
            isCurrentMonth: false,
            isToday: false,
            events: [],
            hasEvents: false
          });
        }
        
        // 当前月的日期
        for (let i = 1; i <= daysInMonth; i++) {
          const dateString = `${currentYear}-${(currentMonth + 1).toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`;
          
          // 过滤当天事件
          let events = allEvents.filter(event => event.date === dateString);
          
          // 根据礼服编号筛选
          if (dressCode) {
            events = events.filter(event => event.dressCode === dressCode);
          }
          
          // 根据类型过滤
          if (currentFilter !== 'all') {
            events = events.filter(event => event.type === currentFilter);
          }
          
          calendarDays.push({
            day: i,
            dateString: dateString,
            isCurrentMonth: true,
            isToday: isCurrentMonth && i === todayDate,
            events: events,
            hasEvents: events.length > 0
          });
        }
        
        // 下个月的日期
        const daysNeeded = 42 - calendarDays.length; // 6行7列
        for (let i = 1; i <= daysNeeded; i++) {
          const nextMonth = currentMonth === 11 ? 0 : currentMonth + 1;
          const nextYear = currentMonth === 11 ? currentYear + 1 : currentYear;
          const dateString = `${nextYear}-${(nextMonth + 1).toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`;
          
          calendarDays.push({
            day: i,
            dateString: dateString,
            isCurrentMonth: false,
            isToday: false,
            events: [],
            hasEvents: false
          });
        }
        
        this.setData({ calendarDays });
    },
    
    // 加载当日事件
    loadDayEvents: function() {
        const { selectedDate, allEvents, currentFilter, dressCode } = this.data;
        
        // 过滤当天事件
        let events = allEvents.filter(event => event.date === selectedDate);
        
        // 根据礼服编号筛选
        if (dressCode) {
          events = events.filter(event => event.dressCode === dressCode);
        }
        
        // 根据类型过滤
        if (currentFilter !== 'all') {
          events = events.filter(event => event.type === currentFilter);
        }
        
        // 按时间排序
        events.sort((a, b) => {
          return a.time.localeCompare(b.time);
        });
        
        this.setData({ dayEvents: events });
    },
    
    // 切换月份
    prevMonth: function() {
        let { currentYear, currentMonth } = this.data;
        
        if (currentMonth === 0) {
          currentMonth = 11;
          currentYear--;
        } else {
          currentMonth--;
        }
        
        this.setData({
          currentYear,
          currentMonth,
          currentMonthDisplay: `${currentYear}年${currentMonth + 1}月`
        });
        
        this.generateCalendarDays();
    },
    
    nextMonth: function() {
        let { currentYear, currentMonth } = this.data;
        
        if (currentMonth === 11) {
          currentMonth = 0;
          currentYear++;
        } else {
          currentMonth++;
        }
        
        this.setData({
          currentYear,
          currentMonth,
          currentMonthDisplay: `${currentYear}年${currentMonth + 1}月`
        });
        
        this.generateCalendarDays();
    },
    
    // 切换过滤器
    switchFilter: function(e) {
        const filter = e.currentTarget.dataset.filter;
        this.setData({ currentFilter: filter });
        
        // 更新日历和事件
        this.generateCalendarDays();
        this.loadDayEvents();
    },
    
    // 切换日历视图
    switchCalendarView: function(e) {
        const view = e.currentTarget.dataset.view;
        this.setData({ calendarView: view });
        
        // 暂时只提示功能开发中
        if (view !== 'month') {
          wx.showToast({
            title: '功能开发中',
            icon: 'none'
          });
        }
    },
    
    // 选择日期
    selectDay: function(e) {
        const date = e.currentTarget.dataset.date;
        
        // 解析日期
        const [year, month, day] = date.split('-');
        
        const displayTitle = this.data.dressName ? 
          `${this.data.dressName} 档期安排` : 
          `档期安排（${month}月${parseInt(day)}日）`;
        
        this.setData({
          selectedDate: date,
          selectedDateDisplay: displayTitle
        });
        
        // 更新当日事件
        this.loadDayEvents();
    },
    
    // 查看事件详情
    viewEventDetail: function(e) {
        const eventId = e.currentTarget.dataset.id;
        wx.navigateTo({
          url: `/pages/event_detail/event_detail?id=${eventId}`
        });
    },
    
    // 显示添加事件选项
    showAddEventOptions: function() {
        wx.showActionSheet({
          itemList: ['预约取件', '预约量体', '预约试装', '预约归还', '安排维护'],
          success: (res) => {
            // 暂时只提示功能开发中
            wx.showToast({
              title: '功能开发中',
              icon: 'none'
            });
          }
        });
    }
})